<?php

namespace app\common\model;

use app\common\service\StockService;
use think\Db;
use think\Exception;
use think\Model;


class AgentShipment extends Model
{

    

    

    // 表名
    protected $name = 'agent_shipment';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'sign_time_text',
	    'status_text'
    ];
    
	const STATUS_WAIT = 0;
	const STATUS_SUCCESS = 1;
	const STATUS_SHIPPING = 2;
	
	public static $statusList = [
		self::STATUS_SUCCESS => '已签收',
		self::STATUS_WAIT => '待签收',
		self::STATUS_SHIPPING => '待配送'
	];
    
	public function getStatusTextAttr($value, $data) {
		$value = $value ? : $data['status'];
		$list = self::$statusList;
		return $list[$value] ?? '';
	}


    public function getSignTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['sign_time']) ? $data['sign_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setSignTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }
	
	public function send() {
		return $this->belongsTo('agentShop', 'send_agent_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function signagent() {
		return $this->belongsTo('agentShop', 'sign_agent_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	
	public function goods() {
		return $this->belongsTo('goods', 'goods_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function spec() {
		return $this->belongsTo('goodsSpec', 'spec_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	/**
	 * 签收入库
	 * @param $no 批次号
	 * @param $agentId 代理ID
	 * @param $userId 用户ID
	 * @return bool
	 * @throws \think\exception\PDOException
	 */
    public function sign($no, $agentId, $userId) {
		$this->startTrans();
		try {
			
			$where = ['sign_agent_id' => $agentId, 'no' => $no, 'status' => self::STATUS_WAIT];
			$orders = Db::name('agentShipment')
				->where($where)
				->select();
			
			if(!$orders) {
				throw new Exception('要签收的订单不存在');
			}
			
			//更改订单状态
			$res = $this->save(['status' => self::STATUS_SUCCESS, 'sign_time' => time()], $where);
			if(!$res) {
				throw new Exception('更改签收状态出错');
			}
			
			$stockModel = new AgentStock();
			$recModel = new AgentStockRecord();
			foreach ($orders as $order) {
				//添加库存
				$numRes = $stockModel->add($userId, $agentId, $order['goods_id'], $order['spec_id'], $order['number']);
				if(!$numRes) {
					throw new Exception('添加库存出错');
				}
				
				//记录库存记录
				$recRes = $recModel->addRecord($userId, $order['goods_id'], $order['spec_id'], $recModel::TYPE_IN, $order['number'], '签收入库');
				if(!$recRes) {
					throw new Exception('添加库存记录出错');
				}
			}
			
			
			$this->commit();
			return true;
		} catch (Exception $e) {
			$this->rollback();
			$this->error = $e->getMessage();
			return false;
		}
    }
	
	
	/**
	 * 获取出入库订单
	 * @param $where
	 * @return array
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
    public function getOrder($where) {
    	
	    $rows = Db::name('agentShipment')->alias('o')
		    ->join('goods g', 'o.goods_id = g.id', 'left')
		    ->join('agentShop a', 'o.sign_agent_id = a.id', 'left')
		    ->join('goodsSpec s', 'o.spec_id = s.id', 'left')
		    ->where($where)
		    ->field('o.id, o.no, o.number, o.ship_name, o.ship_no, o.status, from_unixtime(o.create_time, \'%Y/%m/%d %H:%i:%s\') as date, g.image, g.name, s.name as spec_name, a.name as sign_name')
		    ->order(['o.create_time' => 'DESC'])
		    ->select();
	
	    $orders = [];
	    if($rows) {
		    $statusList = AgentShipment::$statusList;
		    foreach ($rows as $row) {
			    if(!isset($orders[$row['no']])) {
				    $orders[$row['no']] = [
					    'no' => $row['no'],
					    'date' => $row['date'],
					    'ship_name' => $row['ship_name'],
					    'ship_no' => $row['ship_no'],
					    'status' => $row['status'],
					    'status_text' => $statusList[$row['status']],
					    'name' => $row['sign_name'],
					    'goods' => [
					
					    ]
				    ];
			    }
			
			    $orders[$row['no']]['goods'][] = $row;
		    }
	    }
	    
	    return array_values($orders);
    }
    
    
    
}
